#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import glob
import pathlib

try:
    # what to insert (with blank line in the beginning and the end)
    buf2 = r"""
## patched by fpemud-refsystem ####

# don't use password framework, polkit is enough, and we don't need password when boot for encrypted HDD
find "${D}" -name "*ask-password*" | xargs rm -rf
find "${D}" -name "*reply-password*" | xargs rm -rf

# don't use any timer functionality
find "${D}" -name "*.timer" | xargs rm -rf

# clean up tmpfiles
rm -rf ${D}/usr/lib/tmpfiles.d/provision.conf
rm -rf ${D}/usr/lib/tmpfiles.d/systemd-tmp.conf

# remove /etc/sysctl.conf (/usr/lib/sysctl.d/99-sysctl.conf symlinks to /etc/sysctl.conf)
rm -rf ${D}/usr/lib/sysctl.d/99-sysctl.conf

# make systemd record journal in memory only, to eliminate disk writes
rm -rf "${D}/var/log/journal"

# files in /var has already been created by /usr/lib/tmpfiles.d/*.conf
rm -rf "${D}/var"

# remove plymouth in emergency.service
sed -i "/plymouth/d" "${D}/lib/systemd/system/emergency.service"

# remove plymouth in rescue.service
sed -i "s/ *plymouth-start\\.service *//g" "${D}/lib/systemd/system/rescue.service"
sed -i "/plymouth/d"                       "${D}/lib/systemd/system/rescue.service"
## end ####"""
    buf2 = buf2.replace("\n", "\n\t")
    buf2 += "\n"

    for fn in glob.glob("*.ebuild"):
        buf = pathlib.Path(fn).read_text()

        # insert to the end of src_install()
        pos = buf.find("multilib_src_install_all() {")
        if pos == -1:
            raise ValueError()
        pos = buf.find("\n}\n", pos)
        if pos == -1:
            raise ValueError()
        pos += 1

        # do insert
        buf = buf[:pos] + buf2 + buf[pos:]
        with open(fn, "w") as f:
            f.write(buf)
except ValueError:
    print("outdated")
